package main

import (
	"fmt"
	"master_go/mutex/mux"
	"sync"
	"time"
)

var count int = 0
var wg sync.WaitGroup
var mu sync.Mutex

type Counter struct {
	count int
	sync.Mutex
}

func (c *Counter) Incr() {
	c.Lock()
	defer c.Unlock()
	c.count++
}

var val int32

func main1() {
	var c Counter
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for i := 0; i < 100000; i++ {
				c.Incr()
			}
		}()
	}
	wg.Wait()
	fmt.Println(c.count)
	for i := 0; i < 10; i++ {
		go func() {
			val = mux.Xadd(&val, 1)
		}()
	}
	time.Sleep(time.Second)
	fmt.Println(val)

}

type value struct {
	mu  sync.Mutex
	val int
}

func main() {
	wg := sync.WaitGroup{}
	printSum := func(a, b *value) {
		defer wg.Done()
		a.mu.Lock()
		defer a.mu.Unlock()
		time.Sleep(2 * time.Second)
		b.mu.Lock()
		defer b.mu.Unlock()

		fmt.Printf("sum = %v\n", a.val+b.val)
	}

	a := value{val: 1}
	b := value{val: 2}
	wg.Add(2)
	go printSum(&a, &b)
	go printSum(&b, &a)
	wg.Wait()
	// 并发进程彼此等待程序
}
